﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Edit_F4Plan : Form
    {
        public string planid;
        private INISettings mySetting;
        private SqlConnection myConnection;
        private string error;

        public frm_Edit_F4Plan()
        {
            InitializeComponent();
            ModuleWaitDialog.CreateWaitDialog("", "Please waiting...");
            ModuleWaitDialog.SetWaitDialogCaption("Loading data...");
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.error = null;
            this.planid = "";
            if (string.IsNullOrEmpty(error))
            {
                LoadCustomer();
            }

            if (!string.IsNullOrEmpty(error))
            {
                MessageBox.Show(error);
            }
            ModuleWaitDialog.CloseWaitDialog();
        }

        ////////////////////////////////////////////
        /// Load Data for Selected plan
        ////////////////////////////////////////////
        public bool LoadData()
        {
            bool ret = true;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT * FROM [231_TimePlan] WHERE TimePlanNo='" + planid + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    this.txtOrderNo.Text = dataReader["TimePlanNo"].ToString();
                    this.txtPlanNo.Text = dataReader["PlanNo"].ToString();
                    this.txtCompNo.Text = dataReader["CompID"].ToString();
                    this.txtNewComp.Text = dataReader["NewComp"].ToString();
                    this.txtQuantity.Text = dataReader["Quantity"].ToString();
                    this.txtSubOrder1.Text = dataReader["SubOrder1"].ToString();
                    this.txtSubOrder2.Text = dataReader["SubOrder2"].ToString();
                    this.txtSubOrder3.Text = dataReader["SubOrder3"].ToString();
                    this.txtSubOrder4.Text = dataReader["SubOrder4"].ToString();
                    this.txtSubOrder5.Text = dataReader["SubOrder5"].ToString();
                    this.txtSubOrder6.Text = dataReader["SubOrder6"].ToString();

                    for (int i = 0; i < this.cboCustomerID.Properties.Items.Count; i++)
                    {
                        ComboboxItem item = (ComboboxItem)this.cboCustomerID.Properties.Items[i];
                        if (dataReader["CustomerID"].ToString() == item.Value.ToString())
                        {
                            this.cboCustomerID.SelectedIndex = i;
                        }
                    }

                    this.txtFromSerial.Text = dataReader["FromSerialNo"].ToString();
                    this.txtToSerial.Text = dataReader["ToSerialNo"].ToString();

                    if (dataReader["DeadLine"] != DBNull.Value)
                    {
                        this.dtDeadLine.EditValue = DateTime.Parse(dataReader["DeadLine"].ToString());
                    }
                    if (dataReader["FinishedDate"] != DBNull.Value)
                    {
                        this.dtFinishedDate.EditValue = DateTime.Parse(dataReader["FinishedDate"].ToString());
                    }
                    this.txtUnitTime.Text = dataReader["UnitTime"].ToString();
                    this.txtRemarks.Text = dataReader["Remark"].ToString();
                }
                else
                {
                    ret = false;
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                ret = false;
                error = "Cannot get data for selected plan";
            }

            return ret;
        }

        ////////////////////////////////////////////
        /// Load Customer List
        ////////////////////////////////////////////
        private void LoadCustomer()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CustomerID, CustomerName FROM [231_Customer] ORDER BY CustomerName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CustomerID"].ToString() + " | " + dataReader["CustomerName"].ToString() + ")";
                    item.Value = dataReader["CustomerID"].ToString();
                    this.cboCustomerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Customer list";
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            error = null;
            int quantity = 0;
            int unittime = 0;
            DateTime deadline;
            DateTime finished_date = new DateTime();
            string start_serial = null;
            string end_serial = null;
            string customer = null;
            string remark = null;

            ComboboxItem item = new ComboboxItem();
            
            if (string.IsNullOrEmpty(error))
            {
                if (!Int32.TryParse(this.txtQuantity.Text, out quantity))
                {
                    error = "Invalid Quantity";
                }
                else
                {
                    if (quantity <= 0)
                    {
                        error = "Quantity must be greater than 0";
                    }
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.dtDeadLine.EditValue == null)
                {
                    error = "Please select Dead Line";
                }
                else
                {
                    deadline = DateTime.Parse(this.dtDeadLine.EditValue.ToString());
                }
            }


            start_serial = this.txtFromSerial.Text;
            if (string.IsNullOrEmpty(start_serial))
            {
                start_serial = null;
            }

            end_serial = this.txtToSerial.Text;
            if (string.IsNullOrEmpty(end_serial))
            {
                end_serial = null;
            }

            
            if (string.IsNullOrEmpty(error))
            {
                if (this.cboCustomerID.SelectedIndex < 0)
                {
                    customer = null;
                }
                else
                {
                    item = (ComboboxItem)this.cboCustomerID.SelectedItem;
                    customer = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                remark = this.txtRemarks.Text;
                if (string.IsNullOrEmpty(error))
                {
                    if (this.dtFinishedDate.EditValue != null)
                    {
                        finished_date = DateTime.Parse(this.dtFinishedDate.EditValue.ToString());
                    }
                }
                try
                {
                    deadline = DateTime.Parse(this.dtDeadLine.EditValue.ToString());
                    myConnection.Open();
                    string sql = "UPDATE [231_TimePlan] SET "
                        + "CompID='" + txtCompNo .Text  +"', "
                        + "NewComp='" + txtNewComp.Text + "', "
                        + "Quantity=" + quantity + ", "
                        + "SubOrder1='" + txtSubOrder1.Text + "', "
                        + "SubOrder2='" + txtSubOrder2.Text + "', "
                        + "SubOrder3='" + txtSubOrder3.Text + "', "
                        + "SubOrder4='" + txtSubOrder4.Text + "', "
                        + "SubOrder5='" + txtSubOrder5.Text + "', "
                        + "SubOrder6='" + txtSubOrder6.Text + "', "
                        + "CustomerID='" + customer + "', "
                        + "FromSerialNo='" + start_serial + "', "
                        + "ToSerialNo='" + end_serial + "', "
                        + "DeadLine=@deadline, "
                        + "FinishedDate=@finisheddate, "
                        + "UnitTime=" + unittime + ", "
                        +" Remark='" + remark + "'"
                        + " WHERE TimePlanNo='" + planid + "'";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@deadline", SqlDbType.DateTime).Value = deadline.Date;
                    if (this.dtFinishedDate.EditValue != null)
                    {
                        cmd_sql.Parameters.Add("@finisheddate", SqlDbType.DateTime).Value = finished_date.Date;
                    }
                    else
                    {
                        cmd_sql.Parameters.Add("@finisheddate", SqlDbType.DateTime).Value = DBNull.Value;
                    }
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("F4 Plan updated success.");
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                    //MessageBox.Show("Cannot update F4 Plan. Please try again.");
                }
            }
            else
            {
                MessageBox.Show(error);
            }
        }
    }
}
